<template>
	<view class="container">
		<!-- 顶部操作栏 -->
		<view class="header">
			<view class="cancel-btn" @tap="goBack">取消</view>
			<view class="publish-btn" @tap="handlePublish">发布</view>
		</view>
		
		<!-- 帖子内容 -->
		<scroll-view 
			class="content-scroll" 
			scroll-y="true"
			:style="{ height: 'calc(100vh - 88rpx)' }"  
		>
			<!-- 标题输入 -->
			<view class="title-input">
				<input 
					type="text"
					v-model="formData.title"
					placeholder="请输入标题"
					placeholder-class="placeholder"
					maxlength="50"
				/>
				<text class="word-count">{{ formData.title.length }}/50</text>
			</view>
			
			<!-- 内容输入 -->
			<view class="content-input">
				<textarea 
					v-model="formData.content"
					placeholder="请输入正文内容"
					placeholder-class="placeholder"
					maxlength="5000"
					:show-confirm-bar="false"
					:style="{ width: '100%' }" 
					auto-height
				/>
				<text class="word-count">{{ formData.content.length }}/5000</text>
			</view>
			
			<!-- 封面图 -->
			<view class="cover-upload">
				<view class="upload-box" @tap="chooseCover" v-if="!formData.cover">
					<uni-icons type="image" size="30" color="#999"></uni-icons>
					<text class="tip">添加封面图</text>
				</view>
				<view class="preview-box" v-else>
					<image 
						:src="formData.cover" 
						mode="aspectFill" 
						class="preview-image"
					></image>
					<view class="delete-btn" @tap="removeCover">
						<uni-icons type="trash" size="20" color="#fff"></uni-icons>
					</view>
				</view>
			</view>
			
			<!-- 分类选择 -->
			<view class="category-select">
				<view class="label-wrapper">
					<text class="label">选择分类</text>
					<view class="add-category" @tap="showAddCategory" v-if="isAdmin">
						<uni-icons type="plus" size="16" color="#999"></uni-icons>
						<text>新增</text>
					</view>
				</view>
				<picker 
					:range="categories" 
					range-key="name"
					@change="handleCategoryChange"
				>
					<view class="picker-value">
						<text>{{ selectedCategory ? selectedCategory.name : '请选择分类' }}</text>
						<uni-icons type="right" size="16" color="#999"></uni-icons>
					</view>
				</picker>
			</view>
			
			<!-- 新增分类弹窗 -->
			<view class="add-category-popup" v-if="showAddCategoryPopup">
				<view class="mask" @tap="hideAddCategory"></view>
				<view class="popup-content">
					<view class="popup-header">
						<text class="title">新增分类</text>
						<text class="close-btn" @tap="hideAddCategory">×</text>
					</view>
					<view class="popup-body">
						<input
							v-model="newCategoryName"
							class="category-input"
							placeholder="请输入分类名称"
							:focus="showAddCategoryPopup"
							@confirm="confirmAddCategory"
							:disabled="isCreatingCategory"
						/>
					</view>
					<view class="popup-footer">
						<text 
							class="cancel-btn" 
							@tap="hideAddCategory"
							:style="{ opacity: isCreatingCategory ? '0.5' : '1' }"
							:disabled="isCreatingCategory"
						>取消</text>
						<text 
							class="confirm-btn" 
							@tap="confirmAddCategory"
							:style="{ opacity: isCreatingCategory ? '0.5' : '1' }"
							:disabled="isCreatingCategory"
						>
							<text v-if="isCreatingCategory">创建中...</text>
							<text v-else>确定</text>
						</text>
					</view>
				</view>
			</view>
			
			<!-- 底部占位,防止内容被遮挡 -->
			<view style="height: 40rpx;"></view>
		</scroll-view>
		
		<!-- 发布确认弹窗 -->
		<message-box
			ref="publishMessageBox"
			title="发布帖子"
			message="确定要发布这篇帖子吗？"
			cancelText="再想想"
			confirmText="发布"
			confirmColor="#ff6b6b"
			@confirm="publishPost"
		/>
		
		<!-- 返回确认弹窗 -->
		<message-box
			ref="backMessageBox"
			title="放弃编辑"
			message="是否放弃编辑当前内容？"
			cancelText="继续编辑"
			confirmText="放弃"
			confirmColor="#ff6b6b"
			@confirm="confirmGoBack"
		/>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { api } from '@/utils/request'
import MessageBox from '@/components/MessageBox.vue'
// 加载本地用户信息
let userInfo = uni.getStorageSync('userInfo')
// 表单数据
const formData = ref({
	title: '',
	content: '',
	cover: '',
	category: null
})

// 分类列表
const categories = ref([])
// 选中的分类
const selectedCategory = ref(null)
// 消息弹窗
const publishMessageBox = ref(null)
const backMessageBox = ref(null)
// 是否正在发布
const isPublishing = ref(false)

// 新增分类相关
const showAddCategoryPopup = ref(false)
const newCategoryName = ref('')
const isCreatingCategory = ref(false)

// 是否是管理员
const isAdmin = ref(false)

// 检查是否是管理员
const checkIsAdmin = async () => {
	try {
		const res = await api.request({
			url: '/api/users/admin/is_super_admin/',
			method: 'GET',
			data: {
				user_id: userInfo.user_id
			}
		})
		
		if(res.code === 200) {
			isAdmin.value = res.data === true
		}
	} catch(err) {
		console.error('检查管理员权限失败', err)
		isAdmin.value = false
	}
}

// 获取分类列表
const getCategories = async () => {
	try {
		const res = await api.request({
			url: '/api/post/get_category/',
			method: 'GET'
		})
		
		if(res.code === 200) {
			categories.value = res.data
		}
	} catch(err) {
		console.error('获取分类失败', err)
		uni.showToast({
			title: '获取分类失败',
			icon: 'none'
		})
	}
}

// 选择封面
const chooseCover = async () => {
	try {
		const res = await uni.chooseImage({
			count: 1,
			sizeType: ['compressed'],
			sourceType: ['album', 'camera']
		})
		formData.value.cover = res.tempFilePaths[0]
	} catch(err) {
		console.error('选择图片失败', err)
	}
}

// 移除封面
const removeCover = () => {
	formData.value.cover = ''
}

// 分类改变
const handleCategoryChange = (e) => {
	const index = e.detail.value
	selectedCategory.value = categories.value[index]
	formData.value.category = categories.value[index].id
}

// 返回
const goBack = () => {
	if(formData.value.title || formData.value.content || formData.value.cover) {
		backMessageBox.value.show()
	} else {
		uni.navigateBack()
	}
}

// 确认返回
const confirmGoBack = () => {
	uni.navigateBack()
}

// 处理发布
const handlePublish = () => {
	// 表单验证
	if(!formData.value.title.trim()) {
		uni.showToast({
			title: '请输入标题',
			icon: 'none'
		})
		return
	}
	
	if(!formData.value.content.trim()) {
		uni.showToast({
			title: '请输入内容',
			icon: 'none'
		})
		return
	}
	
	if(!formData.value.category) {
		uni.showToast({
			title: '请选择分类',
			icon: 'none'
		})
		return
	}

    // 检查是否正在发布
	if(isPublishing.value) return

    // 判断是否登录
	if(!userInfo) {
		uni.showToast({
			title: '请先登录',
			icon: 'none'
		})
		return
	}

    // 查看有没有用户的user_id
	if(!userInfo.user_id) {
		uni.showToast({
			title: '用户信息获取失败',
			icon: 'none'
		})
		return
	}
	
	publishMessageBox.value.show()
}

// 发布帖子
const publishPost = async () => {
	if(isPublishing.value) return
	
	isPublishing.value = true
	try {
		// 如果有封面图,使用 uploadFile
		if(formData.value.cover) {
			await new Promise((resolve, reject) => {
				uni.uploadFile({
					url: api.BASE_URL + '/api/post/create_post/',
					filePath: formData.value.cover,
					name: 'cover',
					formData: {
						title: formData.value.title,
						content: formData.value.content,
						category: formData.value.category,
						user_id: userInfo.user_id
					},
					success: (uploadRes) => {
						const data = JSON.parse(uploadRes.data)
						if(data.code === 200) {
							resolve(data)
						} else {
							reject(new Error(data.message))
						}
					},
					fail: reject
				})
			})
		} else {
			// 无封面图直接发送请求
			const res = await api.request({
				url: '/api/post/create_post/',
				method: 'POST',
				data: {
					title: formData.value.title,
					content: formData.value.content,
					category: formData.value.category,
					user_id: userInfo.user_id
				}
			})
			
			if(res.code !== 200) {
				throw new Error(res.message)
			}
		}
		
		uni.showToast({
			title: '发布成功',
			icon: 'success'
		})
		
		setTimeout(() => {
			uni.navigateBack()
		}, 1500)
		
	} catch(err) {
		console.error('发布失败', err)
		uni.showToast({
			title: err.message || '发布失败',
			icon: 'none'
		})
	} finally {
		isPublishing.value = false
	}
}

// 显示新增分类弹窗
const showAddCategory = () => {
	newCategoryName.value = ''
	showAddCategoryPopup.value = true
}

// 隐藏新增分类弹窗
const hideAddCategory = () => {
	showAddCategoryPopup.value = false
}

// 确认新增分类
const confirmAddCategory = async () => {
	if(!newCategoryName.value.trim()) {
		uni.showToast({
			title: '请输入分类名称',
			icon: 'none'
		})
		return
	}
	
	if(isCreatingCategory.value) return
	
	isCreatingCategory.value = true
	try {
		const res = await api.request({
			url: '/api/post/create_category/',
			method: 'POST',
			data: {
				name: newCategoryName.value.trim()
			}
		})
		
		if(res.code === 200) {
			uni.showToast({
				title: '创建成功',
				icon: 'success'
			})
			// 刷新分类列表
			getCategories()
			// 自动选中新创建的分类
			selectedCategory.value = res.data
			formData.value.category = res.data.id
			// 隐藏弹窗
			hideAddCategory()
		}
	} catch(err) {
		console.error('创建分类失败', err)
		uni.showToast({
			title: err.message || '创建失败',
			icon: 'none'
		})
	} finally {
		isCreatingCategory.value = false
	}
}

onMounted(async () => {
	try {
		// 先检查管理员权限
		await checkIsAdmin()
		// 再获取分类列表
		await getCategories()
	} catch(err) {
		console.error('初始化失败', err)
		uni.showToast({
			title: '加载失败',
			icon: 'none'
		})
	}
})
</script>

<style lang="scss" scoped>
.container {
	min-height: 100vh;
	background: #fff;
	height: 100vh;  /* 限制容器高度 */
	display: flex;
	flex-direction: column;
	overflow: hidden;  /* 防止内容溢出 */
}

.header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 30rpx;
	border-bottom: 1rpx solid #eee;
	height: 88rpx;  /* 固定header高度 */
	box-sizing: border-box;
	
	.cancel-btn {
		font-size: 28rpx;
		color: #999;
		
		&:active {
			opacity: 0.7;
		}
	}
	
	.publish-btn {
		background: #ff6b6b;
		color: #fff;
		font-size: 28rpx;
		padding: 12rpx 30rpx;
		border-radius: 30rpx;
		
		&:active {
			opacity: 0.8;
		}
	}
}

.content-scroll {
	flex: 1;
	padding: 30rpx;
	box-sizing: border-box;
	overflow-x: hidden;  /* 防止水平滚动 */
}

.title-input {
	position: relative;
	margin-bottom: 30rpx;
	
	input {
		font-size: 32rpx;
		color: #333;
		font-weight: bold;
		width: 100%;  /* 确保输入框不溢出 */
		box-sizing: border-box;
	}
	
	.word-count {
		position: absolute;
		right: 0;
		bottom: -30rpx;
		font-size: 24rpx;
		color: #999;
	}
}

.content-input {
	position: relative;
	margin-bottom: 40rpx;
	
	textarea {
		font-size: 28rpx;
		color: #333;
		line-height: 1.5;
		min-height: 200rpx;
		width: 100%;
		box-sizing: border-box;
	}
	
	.word-count {
		position: absolute;
		right: 0;
		bottom: -30rpx;
		font-size: 24rpx;
		color: #999;
	}
}

.cover-upload {
	margin-bottom: 40rpx;
	
	.upload-box {
		width: 200rpx;
		height: 200rpx;
		background: #f5f5f5;
		border-radius: 12rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		
		.tip {
			font-size: 24rpx;
			color: #999;
			margin-top: 10rpx;
		}
		
		&:active {
			opacity: 0.7;
		}
	}
	
	.preview-box {
		position: relative;
		width: 200rpx;
		height: 200rpx;
		border-radius: 12rpx;
		overflow: hidden;
		
		.preview-image {
			width: 100%;
			height: 100%;
		}
		
		.delete-btn {
			position: absolute;
			top: 10rpx;
			right: 10rpx;
			width: 40rpx;
			height: 40rpx;
			background: rgba(0, 0, 0, 0.5);
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;
			
			&:active {
				opacity: 0.7;
			}
		}
	}
}

.category-select {
	.label-wrapper {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
		
		.label {
			font-size: 28rpx;
			color: #333;
		}
		
		.add-category {
			display: flex;
			align-items: center;
			gap: 4rpx;
			padding: 10rpx;
			
			text {
				font-size: 24rpx;
				color: #999;
			}
			
			&:active {
				opacity: 0.7;
			}
		}
	}
	
	.picker-value {
		height: 80rpx;
		background: #f5f5f5;
		border-radius: 12rpx;
		padding: 0 30rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		
		text {
			font-size: 28rpx;
			color: #333;
		}
	}
}

.placeholder {
	color: #999;
}

// 新增分类弹窗样式
.add-category-popup {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	z-index: 999;
	display: flex;
	align-items: center;
	justify-content: center;
	
	.mask {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		backdrop-filter: blur(4px);
	}
	
	.popup-content {
		position: relative;
		width: 560rpx;
		background: #fff;
		border-radius: 24rpx;
		overflow: hidden;
		animation: slideIn 0.2s ease-out;
		
		.popup-header {
			padding: 30rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			border-bottom: 1rpx solid #eee;
			
			.title {
				font-size: 32rpx;
				color: #333;
				font-weight: bold;
			}
			
			.close-btn {
				font-size: 40rpx;
				color: #999;
				padding: 0 10rpx;
				
				&:active {
					opacity: 0.7;
				}
			}
		}
		
		.popup-body {
			padding: 30rpx;
			
			.category-input {
				height: 80rpx;
				background: #f5f5f5;
				border-radius: 12rpx;
				padding: 0 20rpx;
				font-size: 28rpx;
				color: #333;
			}
		}
		
		.popup-footer {
			display: flex;
			border-top: 1rpx solid #eee;
			
			text {
				flex: 1;
				height: 100rpx;
				line-height: 100rpx;
				text-align: center;
				font-size: 32rpx;
				
				&.cancel-btn {
					color: #999;
					border-right: 1rpx solid #eee;
				}
				
				&.confirm-btn {
					color: #ff6b6b;
				}
				
				&:active {
					opacity: 0.7;
				}
				
				&:disabled {
					pointer-events: none;
				}
			}
		}
	}
}

@keyframes slideIn {
	from {
		transform: translateY(30rpx);
		opacity: 0;
	}
	to {
		transform: translateY(0);
		opacity: 1;
	}
}
</style>
